package liu.de.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * @author liude
 */
@Configuration
@Slf4j
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) {
                //对于code!=200的不做处理
                try {
                    String responseText = IOUtils.toString(response.getBody());
                    log.debug("status={}, text={}", response.getStatusCode(), responseText);
                } catch (IOException e) {
                    log.error("error in restTemplate, response=" + response, e);
                }
            }
        });
        return restTemplate;
    }
}
